const UPDATE_TITLE_TEXT = 'UPDATE_TITLE_TEXT';
const UPDATE_CONTENT_BG = 'UPDATE_CONTENT_BG';

function createStore(reducer) {
    let state;
    let listeners = [];
    function getState() {
        return state;
    }
    function dispatch(action) {
        state = reducer(state, action);
        listeners.forEach(l => l());
    }
    function subscribe(listener) {
        listeners.push(listener);
        return function() {
            listeners = listeners.filter(item => item !== listener);
        }
    }
    dispatch({ type: '@INIT' });

    return {
        getState,
        dispatch,
        subscribe
    }
}

/* ------------------------------------------------------------------- */

let initState = {
    title: {
        text: 'new title text',
        bg: 'lightblue'
    },
    content: {
        text: 'content',
        bg: 'gold'
    }
}

function reducer(state = initState, action) {
    switch (action.type) {
        case UPDATE_TITLE_TEXT:
            return { ...state, title: { ...state.title, text: action.text } };
        case UPDATE_CONTENT_BG:
            return { ...state, content: { ...state.content, bg: action.bg } }
        default:
            return state;
    }
}

/* ------------------------------------------------------------------- */


let store = createStore(reducer);

function renderTitle() {
    const state = store.getState();
    const title = window.title;
    title.innerHTML = state.title.text;
}
function renderContent() {
    const state = store.getState();
    const content = window.content;
    content.style.backgroundColor = state.content.bg;
}

let unSubscribeTiele = store.subscribe(renderTitle);
let unSubscribeContent = store.subscribe(renderContent);

unSubscribeTiele();

setTimeout(() => {
    store.dispatch({ type: 'UPDATE_CONTENT_BG', bg: 'lightblue' });
    store.dispatch({ type: 'UPDATE_TITLE_TEXT', text: '新的文字' });
}, 2000);
